package com.waji.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.waji.activity.MainActivity;

import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class UpdateManager {
	private static UpdateManager manager = null;
	String Url;

	private UpdateManager() {
	}

	public static UpdateManager getInstance() {
		manager = new UpdateManager();
		return manager;
	}

	public int getVersion(Context context) {
		int version = 0;
		try {
			version = context.getPackageManager().getPackageInfo(
					"com.jiankong.activity", 0).versionCode;
		} catch (Exception e) {
			System.out.println("获取版本号异常！");
			ToMain();
		}
		return version;
	}

	public String getVersionName(Context context) {
		String versionName = null;
		try {
			versionName = context.getPackageManager().getPackageInfo(
					"com.jiankong.activity", 0).versionName;
		} catch (Exception e) {
			ToMain();
			System.out.println("获取版本名异常！");
		}
		return versionName;
	}

	public String getServerVersion() {
		String serverJson = null;
		byte[] buffer = new byte[128];

		try {
			URL serverURL = new URL("http://10.129.55.180:8080/admin/ver.aspx");
			HttpURLConnection connect = (HttpURLConnection) serverURL
					.openConnection();
			BufferedInputStream bis = new BufferedInputStream(
					connect.getInputStream());
			int n = 0;
			while ((n = bis.read(buffer)) != -1) {
				serverJson = new String(buffer);
			}
		} catch (Exception e) {
			ToMain();
			System.out.println("获取服务器版本号异常！" + e);
		}
		return serverJson;
	}

	public boolean CheckVersion(final Context context) {
		new Thread() {
			public void run() {
				Looper.prepare();
				String serverJson = manager.getServerVersion();
				try {
					JSONArray array = new JSONArray(serverJson);
					JSONObject object = array.getJSONObject(0);
					String getServerVersion = object.getString("version");
					Url = object.getString("url");
					String getServerVersionName = object
							.getString("versionName");

					MainActivity.serverVersion = Integer
							.parseInt(getServerVersion);
					MainActivity.serverVersionName = getServerVersionName;

					if (MainActivity.version < MainActivity.serverVersion) {
                        new Thread() {
							public void run() {
								Looper.prepare();
								downloadApkFile(context);
								Looper.loop();
							};
						}.start();

					} else {
						 ToMain();
					}
				} catch (JSONException e) {
					e.printStackTrace();
					ToMain();
					System.out.println("获取服务器版本线程异常！" + e);
				}
				Looper.loop();
			};
		}.start();
		return false;
	}

	public void ToMain() {
		Message msg = new Message();
		msg.what = 0;
		MainActivity.checkhandler.sendMessage(msg);
	}

	public void downloadApkFile(Context context) {
		String savePath = Environment.getExternalStorageDirectory()
				+ "/nihao.apk";

		try {
			if (Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())) {
				URL serverURL = new URL(Url);
				HttpURLConnection connect = (HttpURLConnection) serverURL
						.openConnection();
				BufferedInputStream bis = new BufferedInputStream(
						connect.getInputStream());
				File apkfile = new File(savePath);
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(apkfile));

				int fileLength = connect.getContentLength();
				int downLength = 0;
				int progress = 0;
				int n;
				byte[] buffer = new byte[1024];
				while ((n = bis.read(buffer, 0, buffer.length)) != -1) {
					bos.write(buffer, 0, n);
					downLength += n;
					progress = (int) (((float) downLength / fileLength) * 100);
					Message msg = new Message();
					msg.what = 1;
					msg.arg1 = progress;
					MainActivity.checkhandler.sendMessage(msg);

				}
				bis.close();
				bos.close();
				connect.disconnect();
			}

		} catch (Exception e) {
			System.out.println("下载出错！" + e);
		}
	}
}
